package com.bm.main;

import com.bm.util.MrArrayConverter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author Mirza at Bimasakti
 */
public class SocketClient {

    private Socket socket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private String message;

    public SocketClient(Socket socket) {
        this.socket = socket;
    }

    public MrArrayConverter paramConverter(String methodName, Object[] param) {
        Object[] converted = new Object[param.length + 1];
        for (int i = 0; i < converted.length; i++) {
            if (i == 0) {
                converted[i] = methodName;
            } else {
                converted[i] = param[i - 1];
            }
        }
        MrArrayConverter ma = new MrArrayConverter(converted);
        return ma;
    }

    public Object execute(String methodName, Object[] param) {
        try {
            out = new ObjectOutputStream(socket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(socket.getInputStream());
            try {
                MrArrayConverter ma = paramConverter(methodName, param);
                sendMessage(ma);
                Object o = in.readObject();
                if (o != null) {
                    return o;
                } else {
                    return "";
                }

            } catch (ClassNotFoundException classNot) {
                //System.err.println("data received in unknown format");
            }
        } catch (IOException ex) {
            Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                socket.close();
            } catch (IOException ex) {
                Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    private void sendMessage(MrArrayConverter msg) {
        try {
            out.writeObject(msg);
            out.flush();
        } catch (IOException ioException) {
        }
    }
}
